package com.xuecheng.content.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.base.exception.XuChengException;
import com.xuecheng.content.mapper.TeachplanMapper;
import com.xuecheng.content.mapper.TeachplanMediaMapper;
import com.xuecheng.content.model.dto.SaveOrUpdateTeachPlanDto;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.mapper.TeachPlanMapperStruct;
import com.xuecheng.content.model.po.Teachplan;
import com.xuecheng.content.model.po.TeachplanMedia;
import com.xuecheng.content.service.TeachplanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 课程计划 服务实现类
 * </p>
 *
 * @author luhao
 */
@Slf4j
@Service
public class TeachplanServiceImpl extends ServiceImpl<TeachplanMapper, Teachplan> implements TeachplanService {
    @Autowired
    private TeachPlanMapperStruct teachPlanMapperStruct;
    @Autowired
    private TeachplanMediaMapper teachplanMediaMapper;

    @Override
    public List<TeachplanDto> queryTeachPlanByTreeNodes(Long courseId) {
        List<TeachplanDto> teachplanDtos = this.baseMapper.selectTeachPlanByTreeNodes(courseId);
        return teachplanDtos;
    }

    @Override
    @Transactional
    public boolean addOrAmendTeachPlan(SaveOrUpdateTeachPlanDto dto) {
        // 实体类转换
        Teachplan teachPlan = teachPlanMapperStruct.toTeachPlan(dto);
        if (teachPlan.getId() == null) {
            // 根据父类信息和等级查询出教学计划总数
            LambdaQueryWrapper<Teachplan> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Teachplan::getParentid, teachPlan.getParentid())
                    .eq(Teachplan::getCourseId, teachPlan.getCourseId())
                    .eq(Teachplan::getGrade, teachPlan.getGrade());
            Integer count = baseMapper.selectCount(wrapper);
            // 排序数加1
            teachPlan.setOrderby(++count);
            teachPlan.setChangeDate(LocalDateTime.now());
            teachPlan.setCreateDate(LocalDateTime.now());
            int insert = baseMapper.insert(teachPlan);
            return insert > 0;
        } else {
            // 存在课程计划id,则修改
            teachPlan.setChangeDate(LocalDateTime.now());
            int updateById = baseMapper.updateById(teachPlan);
            return updateById > 0;
        }
    }

    @Override
    @Transactional
    public boolean removeTeachPlanById(Long coursePlanId) {
        // 根据课程计划id查询课程计划
        Teachplan teachplan = baseMapper.selectById(coursePlanId);
        if (teachplan == null) {
            XuChengException.cast("该课程计划为空");
        }
        // 获取parentId
        if (teachplan.getParentid() == 0) {
            // 查询子课程计划
            LambdaQueryWrapper<Teachplan> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Teachplan::getParentid, coursePlanId);
            List<Teachplan> teachplans = baseMapper.selectList(wrapper);
            if (CollectionUtil.isNotEmpty(teachplans)) {
                XuChengException.cast("课程计划信息还有子级信息，无法操作", "120409");
            }
            // 删除课程计划
            int deleteById = baseMapper.deleteById(coursePlanId);
            if (deleteById <= 0) {
                XuChengException.cast("删除父级课程计划有误");
            }
        } else {
            // 删除课程计划
            int deleteTeachPlan = baseMapper.deleteById(coursePlanId);
            if (deleteTeachPlan <= 0) {
                XuChengException.cast("删除子课程计划有误");
            }
            // 根据课程计划删除课程媒体信息
            LambdaQueryWrapper<TeachplanMedia> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TeachplanMedia::getTeachplanId, teachplan.getId());
            teachplanMediaMapper.delete(wrapper);
        }
        return true;
    }

    @Override
    @Transactional
    public boolean moveUpTeachPlanById(Long coursePlanId) {
        // 根据课程计划查询课程计划信息
        Teachplan teachplan = baseMapper.selectById(coursePlanId);
        Integer orderby = teachplan.getOrderby();
        if (orderby == 1) {
            XuChengException.cast("课程计划已为第一，无法上移");
        }
        // 修改排序-1的课程计划
        LambdaUpdateWrapper<Teachplan> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Teachplan::getParentid, teachplan.getParentid()).
                eq(Teachplan::getCourseId, teachplan.getCourseId()).
                eq(Teachplan::getOrderby, orderby - 1).set(Teachplan::getOrderby, orderby)
                .set(Teachplan::getChangeDate,LocalDateTime.now());
        // 修改课程计划排序字段
        int updateTeachPlan = baseMapper.update(null, updateWrapper);
        updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Teachplan::getId, teachplan.getId()).set(Teachplan::getOrderby, orderby - 1)
                .set(Teachplan::getChangeDate,LocalDateTime.now());
        int updateLastTeachPlan = baseMapper.update(null, updateWrapper);
        if (updateTeachPlan <= 0 || updateLastTeachPlan <= 0) {
            XuChengException.cast("修改课程计划排序失败");
        }
        return true;
    }

    @Override
    @Transactional
    public boolean moveDownTeachPlanById(Long coursePlanId) {
        // 根据课程计划查询课程计划信息
        Teachplan teachplan = baseMapper.selectById(coursePlanId);
        Integer orderby = teachplan.getOrderby();
        // 查询当前父级目录有多少子条目
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getParentid, teachplan.getParentid());
        Integer count = baseMapper.selectCount(queryWrapper);
        if (orderby == count) {
            XuChengException.cast("课程计划为最低级，无法下移");
        }
        // 修改排序加1的课程计划
        LambdaUpdateWrapper<Teachplan> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Teachplan::getParentid, teachplan.getParentid()).
                eq(Teachplan::getCourseId, teachplan.getCourseId()).
                eq(Teachplan::getOrderby, orderby + 1).set(Teachplan::getOrderby, orderby)
                .set(Teachplan::getChangeDate,LocalDateTime.now());
        // 修改课程计划排序字段
        int updateNextTeachPlan = baseMapper.update(null, updateWrapper);
        updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Teachplan::getId, teachplan.getId()).set(Teachplan::getOrderby, orderby + 1)
                .set(Teachplan::getChangeDate,LocalDateTime.now());
        int updateTeachPlan = baseMapper.update(null, updateWrapper);
        if (updateNextTeachPlan <= 0 || updateTeachPlan <= 0) {
            XuChengException.cast("修改课程计划排序失败");
        }
        return true;
    }
}
